package com.example.demo.Controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: H_tao_X
 * Date: 2022-12-02
 * Time: 16:14
 */

@Slf4j
@Controller
@ResponseBody // 返回非静态页面
@RequestMapping("/user3")  // 一级理由
public class UserController3 {

    /**
     * 获取 Cookie 1:
     * @param request
     */
    @RequestMapping("/cookie")
    public void getCookie(HttpServletRequest request) {
        // 得到全部 Cookie
        Cookie[] cookies =  request.getCookies();
        for(Cookie item :cookies) {
            log.info("Cookie Name: " + item.getName() + "Cookie Value: " +
                    item.getValue());
        }
    }

    /**
     * 使用注解获取 Cookie
     */
    @RequestMapping("/cookie2")
    public String getCookie2(@CookieValue("bit") String cookie) {
        return "Cookie Value: " + cookie;
    }


    /**
     * 获取 Header
     */
    // 1. 使用 Servlet
    @RequestMapping("/gethead")
    public String getHead(HttpServletRequest request) {
        return "header: " + request.getHeader("User-Agent");
    }

    // 2. 使用 @RequestHeader
    @RequestMapping("/gethead2")
    public String getHead2(@RequestHeader("User-Agent") String userAgent) {
        return "header: " + userAgent;
    }

    /**
     * 储存 Seesion
     */
    @RequestMapping("/session")
    public boolean setSession(HttpServletRequest request) {
        boolean result = false;
        // 1. 得到 HttpSession
        HttpSession session = request.getSession(true); // true = 如果没有会话，那么创建一个会话
        // 2. 使用 setAtt 设置值
        session.setAttribute("userinfo","张三");
        result = true;
        return result;
    }

    /**
     * 获取 Session 一：
     */
    @RequestMapping("/getsess")
    public String getSession(HttpServletRequest request) {
        String result = null;
        // 1. 得到 HttpSession 对象
        HttpSession session = request.getSession(false); // false = 如果有会话使用，没有不创建
        // 2. getAtt 得到 Session 信息
            // 判空
        if(session != null && session.getAttribute("userinfo")!= null) {
            result = (String) session.getAttribute("userinfo");
        }
        return result;
    }

    /**
     * 获取 Session 二：
     */
    @RequestMapping("/getsess2")
    public String getSession2(@SessionAttribute(value = "userinfo",required = false)
                                          String userinfo) {
        return "会话: " + userinfo;
    }

}
